/**
 * Copyright &copy; 2016-2017 <a href="https://www.lczyfz.com">联创智云</a> All rights reserved.
 */
package com.lczyfz.campusinfo.modules.user.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Pattern;

import javax.mail.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.lczyfz.campusinfo.common.utils.*;
import com.lczyfz.campusinfo.modules.user.dao.CampusinfoGroupDao;
import com.lczyfz.campusinfo.modules.user.utils.PropertiesUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.drew.lang.StringUtil;
import com.lczyfz.campusinfo.common.persistence.Page;
import com.lczyfz.campusinfo.common.service.CrudService;
import com.lczyfz.campusinfo.modules.campusinfo.dao.CampusinfoSchoolDao;
import com.lczyfz.campusinfo.modules.campusinfo.entity.CampusinfoSchool;
import com.lczyfz.campusinfo.modules.frontuser.entity.CampusinfoFrontUser;
import com.lczyfz.campusinfo.modules.frontuser.utils.FrontUserUtils;
import com.lczyfz.campusinfo.modules.sys.entity.User;
import com.lczyfz.campusinfo.modules.sys.security.FormAuthenticationFilter;
import com.lczyfz.campusinfo.modules.sys.security.SystemAuthorizingRealm;
import com.lczyfz.campusinfo.modules.sys.security.UsernamePasswordToken;
import com.lczyfz.campusinfo.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.lczyfz.campusinfo.modules.sys.service.SystemService;
import com.lczyfz.campusinfo.modules.sys.utils.UserUtils;
import com.lczyfz.campusinfo.modules.user.dao.CampusinfoUserDao;
import com.lczyfz.campusinfo.modules.user.dao.CampusinfoUserGroupDao;
import com.lczyfz.campusinfo.modules.user.utils.SendMsg;
import com.lczyfz.campusinfo.modules.user.utils.ServerResponse;
import com.sun.tools.corba.se.idl.constExpr.And;

/**
 * 用户信息Service
 * @author 陈维乾
 * @version 2018-03-31
 */
@Service
@Transactional(readOnly = true)
public class CampusinfoUserService extends CrudService<CampusinfoUserDao, User> {

	@Autowired
	private CampusinfoUserDao campusinfoUserDao;
	
	@Autowired
	private CampusinfoUserGroupDao campusinfoUserGroupDao;

	@Autowired
	private CampusinfoGroupDao campusinfoGroupDao;

	@Autowired
	CampusinfoSchoolDao campusinfoSchoolDao;

	@Autowired
	SystemService systemService;

	//手机正则表达式
	public static final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
	
	
    /**
     * 根据登录名前端用户
     */
    public User getUserByLoginName(String loginName) {
        return UserUtils.getByLoginName(loginName);
    }
	
	public User get(String id) {
		return super.get(id);
	}

	public User getByOpenId(String openId){
    	return campusinfoUserDao.getByOpenId(openId);
	}

	public List<User> findList(User user) {
		return super.findList(user);
	}

	public Page<User> findPage(Page<User> page, User user) {
		return super.findPage(page, user);
	}

	// 获取用户对应组别
	public Page<User> findUserGroupPage(Page<User> page, User user) {
		user.setPage(page);
		List<User> users = dao.findList(user);
		for(User user1:users){
			if(user1.getGroupId() != null && StringUtils.isNotBlank(user1.getGroupId())){
				String Id = user1.getGroupId();
				String[] ids = Id.split(",");
				String groupnames = "";
				for(String id:ids){
					groupnames += campusinfoGroupDao.findNameById(id)+"、";

				}
				user1.setGroupName(groupnames);
			}
		}

		page.setList(users);

		return page;

	}

	@Transactional(readOnly = false)
	public void save(User user) {
		super.save(user);
	}
	@Transactional(readOnly = false)
	public void saveUserAndUserGroup(User user) {
		super.save(user);
	}
	@Transactional(readOnly = false)
	public void delete(User user) {
		super.delete(user);
	}
	
	public List<User> findAllList(User user) {
		return campusinfoUserDao.findAllList(new User());
	}
	
	public User getByIdAndGroupid(String id,String groupId){
		return campusinfoUserDao.getByIdAndGroupid(id,groupId);
	}


	//用户登录判断是否需要验证码
	public ServerResponse<String> isValidatjeesiteLogin(String loginName){
    	//获取缓存
		Map<String, Integer> loginFailMap = (Map<String, Integer>)CacheUtils.get("loginFailMap");

		if(loginFailMap == null){
			return ServerResponse.createBySuccessMessage("不需要验证码登录");
		}
		Integer loginFailNum = loginFailMap.get(loginName);
		System.err.println("loginFailNum"+loginFailNum);
		if (loginFailNum==null){
			return ServerResponse.createBySuccessMessage("不需要验证码登录");
		}
		return ServerResponse.createByErrorMessage("需要验证码登录");
	}

	//获取所有用户
	public List<User> findAllUser(){
		return campusinfoUserDao.findAllUser();
	}
	//判断用户名是否存
	public ServerResponse<String> isUserName(String userName){
		 return this.checkValid(userName,Const.LOGINNAME);
	}
	//判断邮箱是否存
	public ServerResponse<String> isEmail(String email){
		 return this.checkValid(email,Const.EMAIL);
	}


	//TODO用户注册
	@Transactional(readOnly = false)
	public ServerResponse<String> register(User user,String verifyNum,HttpServletRequest request){
        //判断用户名是存在
        ServerResponse<String> validResponse = this.checkValid(user.getLoginName(),Const.LOGINNAME);
        if(!validResponse.isSuccess()){
        	return validResponse;
        }
        //判断邮箱是否存在
        validResponse = this.checkValid(user.getEmail(), Const.EMAIL);
        if (!validResponse.isSuccess()){
            return validResponse;
        }
		//判断手机是否存在
		validResponse = this.checkValid(user.getMobile(), Const.MOBILE);
        System.err.println(validResponse.toString());
		if (!validResponse.isSuccess()){
			return validResponse;
		}
		//1先注释关于手机得信息
        String sessionVerifyNum = (String)request.getSession().getAttribute("VERIFYNUM");
        String sessionMoblie = (String)request.getSession().getAttribute("MOBILE");

        if(sessionVerifyNum == null){
        	return ServerResponse.createByErrorMessage("验证码失效");
        }
        if(!sessionMoblie.equals(user.getMobile())){
            return ServerResponse.createByErrorMessage("注册手机与验证码手机不一致");
        }
        if(!sessionVerifyNum.equalsIgnoreCase(verifyNum)){
        	return ServerResponse.createByErrorMessage("验证码不正确");
        }
        // 给密码加密
        String password =  SystemService.entryptPassword(user.getPassword());
        user.setPassword(password);
        user.setLoginFlag("1");
        user.setUserType("2");//1.管理员用户  2. 普通用户
		user.setId(IdGen.uuid());
		user.setUpdateBy(systemService.getUser("1"));
		user.setCreateBy(systemService.getUser("1"));
		user.setUpdateDate(new Date());
		user.setCreateDate(user.getUpdateDate());
		user.setOpenId(UserUtils.getUser().getOpenId());
        int resultCount = campusinfoUserDao.insertUser(user);
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
    	//清空验证码
//1    	UserUtils.getSession().setAttribute("VERIFYNUM", IdGen.uuid());
        return ServerResponse.createBySuccessMessage("注册成功");
        
	}
	// 短信验证手机号
	public ServerResponse<String> verifyBySendMsg(String mobile ,HttpServletRequest request){
		//先判断手机号的正确性
		Boolean flag = Pattern.matches(REGEX_MOBILE, mobile);
		if(!flag){
			return ServerResponse.createByErrorMessage("输入的手机号码不正确");
		}
		SendMsg sendMsg = new SendMsg();
		String verifyNum = sendMsg.SendMsg(mobile);
		String VALIDTIME= PropertiesUtil.getProperty("VALIDTIME");

		UserUtils.getSession().setAttribute("VERIFYNUM",verifyNum);
		UserUtils.getSession().setAttribute("MOBILE", mobile);
		
		request.getSession().setAttribute("VERIFYNUM",verifyNum);
		request.getSession().setAttribute("MOBILE", mobile);
		request.getSession().setMaxInactiveInterval(Integer.parseInt(VALIDTIME)*60);

		return ServerResponse.createBySuccessMessage("验证码已发送");
	}


	// 忘记密码 ->检验验证码->重设密码
	public ServerResponse<String> forgetResetPassword(String mobile,String verifyNum,String passwordNew,HttpServletRequest request){

        String SessionVerifyNum = (String)request.getSession().getAttribute("VERIFYNUM");
        String sessionMoblie = (String)request.getSession().getAttribute("MOBILE");
        if(SessionVerifyNum == null){
            return ServerResponse.createByErrorMessage("验证码失效");
        }

        if(!sessionMoblie.equals(mobile)){
            return ServerResponse.createByErrorMessage("注册手机与验证码手机不一致");
        }
        if(!SessionVerifyNum.equalsIgnoreCase(verifyNum)){
            return ServerResponse.createByErrorMessage("验证码不正确");
        }
        int resultCount = campusinfoUserDao.updatePasswordByMobile(mobile,passwordNew);

		if(resultCount > 0){
			User user = campusinfoUserDao.getByMobile(mobile);
			user.preUpdate();
			//清空验证码
			UserUtils.getSession().setAttribute("VERIFYNUM", IdGen.uuid());
			return ServerResponse.createBySuccessMessage("重设密码成功");
		}
        return ServerResponse.createByErrorMessage("重设密码失败");
	}


	// 检查当前是否有用户登录
	public ServerResponse<String> hasUser(){
		Principal principal = UserUtils.getPrincipal();
		if(principal != null){
			return ServerResponse.createBySuccessMessage("用户已登录");
		}
		return ServerResponse.createByErrorMessage("用户未登录");
	}

	// 获取用户信息
	public ServerResponse<User> getUserInfo(){
		User user = null;
		SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
		if (principal!=null){
			user = campusinfoUserDao.getUserInfo(principal.getId());

		}

		if(user != null){
			String schoolname = campusinfoSchoolDao.getSchoolNamesById(user.getSchoolId());

			user.setSchoolName(schoolname);

			return ServerResponse.createBySuccess(user);
		}
		return ServerResponse.createByErrorMessage("无法获取当前用户的信息");
	}

	//注册时检查登录用户名/邮箱/手机 是否存在
	public ServerResponse<String> checkValid(String str,String type){
		if(StringUtils.isNotBlank(type)){
			if(Const.LOGINNAME.equals(type)){
				int resultCount = campusinfoUserDao.checkLoginName(str);
				if(resultCount > 0){
					return ServerResponse.createByErrorMessage("用户名已存在");
				}
			}
			if(Const.EMAIL.equals(type)){
				int resultCount = campusinfoUserDao.checkEamil(str);
				if(resultCount > 0){
					return ServerResponse.createByErrorMessage("邮箱已存在");
				}
			}
			if(Const.MOBILE.equals(type)){
				int resultCount = campusinfoUserDao.checkMobile(str);
				if(resultCount > 0){
					return ServerResponse.createByErrorMessage("该手机已注册");
				}
			}
		}else{
			return ServerResponse.createByErrorMessage("参数错误");
		}
		return ServerResponse.createBySuccessMessage("校验成功");
	}
	// 登录状态重设密码
	@Transactional(readOnly = false)
	public ServerResponse<String> resetPassword(String passwordOld,String passwordNew){

		SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
		if (principal == null){
			return ServerResponse.createByErrorMessage("用户未登录");
		}

		//先获取User 然后同loginName 判断密码是否正确
		User user = UserUtils.getUser();
		//加密
		Boolean falg = SystemService.validatePassword(passwordOld,user.getPassword());
        if (!falg) {
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
        String password =  SystemService.entryptPassword(passwordNew);
    	int resultcount = campusinfoUserDao.updatePasswordById(user.getId(), password);
        if(resultcount == 0 ){
        	return ServerResponse.createByErrorMessage("密码更新失败");
        }
		user.preUpdate();

		//改完密码退出
//		UserUtils.getSubject().logout();
//		System.err.println(UserUtils.getSubject());
//		System.err.println(UserUtils.getUser());
		//清除缓存
		UserUtils.clearCache(user);
	//	改完密码退出
		UserUtils.getSubject().logout();
    	return ServerResponse.createBySuccessMessage("密码更新成功，请重新登录");
	}
	//更新个人信息  学校 姓名 学号 邮箱 手机
	@Transactional(readOnly = false)
	public ServerResponse<User> updateInformation(String msg,String type,String verifyNum){

		logger.debug("msg:"+msg);
		logger.debug("type:"+type);
		SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
		if (principal == null){
			return ServerResponse.createByErrorMessage("用户未登录");
		}
		User user = UserUtils.getUser();
		String userId = user.getId();
		//判断类型
		if(Const.SCHOOLID.equalsIgnoreCase(type)){
			//判断是否有效
			if(StringUtils.isNotBlank(msg)){
				campusinfoUserDao.updateSchoolIdByUserId(msg,userId);
			}else {
				return ServerResponse.createByErrorMessage("学校不能为空");
			}
		}
		if(Const.NAME.equalsIgnoreCase(type)){
			if(StringUtils.isNotBlank(msg)){
				campusinfoUserDao.updateNameByUserId(msg,userId);
			}else {
				return ServerResponse.createByErrorMessage("姓名不能为空");
			}
		}
		if(Const.STUID.equalsIgnoreCase(type)){
			if(StringUtils.isNotBlank(msg)){
				campusinfoUserDao.updateStuIdByUserId(msg,userId);
			}else {
				return ServerResponse.createByErrorMessage("学号不能为空");
			}
		}
		//修改手机号  1判断手机格式是否正确  2.先判断手机号是否存在  3 验证码是否正确  4 修改手机号
		if(Const.MOBILE.equalsIgnoreCase(type)){
			if(StringUtils.isNotBlank(msg)){
				//先判断手机号的正确性
				Boolean flag = Pattern.matches(REGEX_MOBILE, msg);
				if(!flag){
					return ServerResponse.createByErrorMessage("输入的手机号码格式不正确");
				}
				//2.1先判断是否与原来相同
		//		System.err.println("1先判断是否与原来相同");
				ServerResponse validResponse = this.checkMobileUpdate(msg);

				if(!validResponse.isSuccess()){
					return validResponse;
				}
				//2.2 判断是否与其他用户相同
		//		System.err.println("判断是否与其他用户相同");
				validResponse = this.checkValid(msg, Const.MOBILE);
				if (!validResponse.isSuccess()){
					return validResponse;
				}
				String sessionVerifyNum = (String)UserUtils.getSession().getAttribute("VERIFYNUM");
				String sessionMoblie = (String)UserUtils.getSession().getAttribute("MOBILE");
				System.err.println("(String)UserUtils.getSession().getAttribute(\"VERIFYNUM\");"+sessionVerifyNum);
				System.err.println("(String)UserUtils.getSession().getAttribute(\"MOBILE\");"+sessionMoblie);
				if(sessionVerifyNum == null){
					return ServerResponse.createByErrorMessage("验证码失效");
				}
				if(user.getMobile()!=null && user.getMobile()!=""){
					if(!sessionMoblie.equals(user.getMobile())){
						return ServerResponse.createByErrorMessage("注册手机与验证码手机不一致");
					}
				}
				if(!sessionVerifyNum.equalsIgnoreCase(verifyNum)){
					return ServerResponse.createByErrorMessage("验证码不正确");
				}
		//		System.err.println("插入数据"+msg+"userId"+userId);
				campusinfoUserDao.updateMobileByUserId(msg,userId);
			}else {
				return ServerResponse.createByErrorMessage("手机不能为空");
			}
		}
		if(Const.EMAIL.equalsIgnoreCase(type)){
			if(StringUtils.isNotBlank(msg)){
				//判断邮箱是否与其他email冲突
				int resultCount = campusinfoUserDao.checkEmailExceptUserId(msg,userId);
				if(resultCount > 0){
					return ServerResponse.createByErrorMessage("邮箱已存在");
				}
				campusinfoUserDao.updateEmailByUserId(msg,userId);
			}else {
				return ServerResponse.createByErrorMessage("邮箱不能为空");
			}
		}
        user.preUpdate();
        //清除缓存
        UserUtils.clearCache(user);
		return ServerResponse.createBySuccessMessage("修改个人信息成功");
	}
	// 判断用户是否实名
	public ServerResponse<String> isVerifyUser(){
    	logger.debug("判断是否实名");
		SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
		if (principal == null) {
			return ServerResponse.createByErrorMessage("用户未登录");
		}
		User currentUser = UserUtils.getUser();
		int resultCount = campusinfoUserDao.checkVerifyUser(currentUser);
		if(resultCount>0){
			return ServerResponse.createBySuccessMessage("用户已实名");
		}
		return ServerResponse.createByErrorMessage("用户未实名");
	}
	//根据微信openid来判断是否存该用户
	public ServerResponse<String> isUserByOpenid(String openid){
		int resultCount = campusinfoUserDao.isUserByOpenid(openid);
		if(resultCount > 0){
			return ServerResponse.createBySuccessMessage("该用户已注册");
		}
    	return ServerResponse.createByErrorMessage("改用户为注册");
	}

	//注册时判断手机是否存在
	public ServerResponse<String> hasMobile(String mobile){
		return this.checkValid(mobile, Const.MOBILE);
	}
	//修改个人信息的手机时 判断手机号是否与原来相同  如果相同 不发验证码 不提交修改  修改按钮是灰色
	public ServerResponse<String> checkMobileUpdate(String mobile){

        SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
        if (principal == null){
            return ServerResponse.createByErrorMessage("用户未登录");
        }
		User user = UserUtils.getUser();
        String id= user.getId();
		String userMoblie = campusinfoUserDao.getMobileById(id);
		//判断是否和原先相同
		if(userMoblie==null){
			return this.checkValid(mobile,Const.MOBILE);
		}
		if(!userMoblie.equals(mobile)){
			//判断是否和其他用户相同
			return this.checkValid(mobile,Const.MOBILE);
		}
		return ServerResponse.createByErrorMessage("不能与原手机一致");
	}
	//获取微信用户根据是否有openid
	public List<User> getWeiXinUser(){

    	return campusinfoUserDao.getWeiXinUser();

    }


}